//
//  NewPersonVC.swift
//  ZYA
//
//  Created by 邱仙凯 on 2024/12/4.
//  Copyright © 2024 zwb. All rights reserved.
//

import UIKit
import JJCollectionViewRoundFlowLayout_Swift
import Kingfisher

class NewPersonVC: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {
     //各项目单独返回
    var expectMenuList:[String] = []

      
//    var expectMenuList = ["我的票夹","我的考勤","我的餐卡","我的邮箱","我的公文","我的薪资","小傲助手"]
    
    lazy var expectMenuList2: [String] = {
        if checkPlatform(type: .zhuYouAn) {
            return ["版本说明", "设置"]
        } else if checkPlatform(type: .aoWang) {
            return ["个人档案", "版本说明", "意见反馈", "设置"]
        } else {
            return ["个人资料", "版本说明", "意见反馈", "设置"]
        }
    }()
    
    private var showMenuItemList = [MenuItem]()
    private var showMenuItemList2 = [MenuItem]()
    lazy var collectionView:UICollectionView = {
       
       
        // 2.创建UICollectionView
        let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: getlayout())
        collectionView.backgroundColor = .clear
        collectionView.showsHorizontalScrollIndicator = false
        
        collectionView.register(NewPersonCell.self, forCellWithReuseIdentifier: NewPersonCell.identifier)
       
        collectionView.register(FunctionCenterHeader.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: FunctionCenterHeader.identifier)
        
        return collectionView
    }()
   
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
      
        navigationController?.setNavigationBarHidden(true, animated: false)
        
        if navigationController?.viewControllers.count ?? 0 <= 1 {
            cv.backButton.isHidden = true
        }

    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(true)
 
        navigationController?.setNavigationBarHidden(false, animated: false)

    }

    func getlayout() -> JJCollectionViewRoundFlowLayout_Swift {
        // 1.创建layout
        let sectionW = self.view.ks_width - 24
        let layout = JJCollectionViewRoundFlowLayout_Swift()
        layout.itemSize = CGSize(width: sectionW/4 - 0.5, height: sectionW/4 - 10)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.sectionInset = UIEdgeInsets(top: 12, left: 12, bottom: 12, right: 12)
        return layout
    }
    
    let img = UIImageView(image: UIImage(named: "icon_t"))
    
    lazy var nameLab:UILabel = {
        let nameLab = UILabel()
        
        nameLab.font = UIFont.boldSystemFont(ofSize: 18)
        return nameLab
    }()
    lazy var companyLab:UILabel = {
        let v = UILabel()
        
        v.font = UIFont.systemFont(ofSize: 16)
        v.textColor = UIColor(kshex: "#444960")
        return v
    }()
    var dotView:DotVView = {
        let v = DotVView()
        v.backgroundColor = UIColor(kshex: "#7487FF")
        v.layer.cornerRadius = 10
        return v
    }()
    
    lazy var deptLab:UILabel = {
        let v = UILabel()
        
        v.font = UIFont.systemFont(ofSize: 15)
        v.textColor = UIColor(kshex: "#8991B0")
        return v
    }()
    
    private lazy var jobRespBtn: BigRangeButton = {
        let btn = BigRangeButton().easy("个人中心-岗位职责说明", self, #selector(jobRespBtnClick))
        return btn as! BigRangeButton
    }()
    
    private var dutyExplain = ""
    
    lazy var header:UIView = {
        let v = UIView(frame:CGRect(x:0,y:-headerH,width:KSGlobal.screenW,height:headerH))
        v.backgroundColor = .clear
        let bottomBg = UIView(frame:CGRect(x:0,y:0,width:KSGlobal.screenW,height:headerH))
        bottomBg.backgroundColor = .clear
        bottomBg.setMutiBorderRoundingCorners(corner: [.topLeft,.topRight], number: 12)
        v.addSubview(bottomBg)
        
        img.extRadius(radius: 30).extMaskBounds(mask: true)
            .extBgColor(color: .white)
        bottomBg.addSubview(img)
        img.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(60)
            make.width.height.equalTo(60)
        }
        
        bottomBg.addSubview(nameLab)
        bottomBg.addSubview(companyLab)
        bottomBg.addSubview(deptLab)
        bottomBg.addSubview(dotView)

        nameLab.snp.makeConstraints { make in
            make.top.equalTo(img.snp.bottom).offset(10)
            make.centerX.equalToSuperview().offset(-16)
        }
        dotView.snp.makeConstraints { make in
            make.left.equalTo(nameLab.snp.right).offset(3)
            make.centerY.equalTo(nameLab)
            make.width.equalTo(32)
            make.height.equalTo(20)
        }
        companyLab.snp.makeConstraints { make in
            make.top.equalTo(nameLab.snp.bottom).offset(8)
            make.centerX.equalToSuperview()
        }
        deptLab.snp.makeConstraints { make in
            make.top.equalTo(companyLab.snp.bottom).offset(8)
            make.centerX.equalToSuperview()
        }
        
        if checkPlatform(type: .aoWang) {
            jobRespBtn.extHidden(hidden: true)
            bottomBg.addSubview(jobRespBtn)
            jobRespBtn.snp.makeConstraints { make in
                make.left.equalTo(deptLab.snp.right)
                make.width.height.equalTo(20)
                make.centerY.equalTo(deptLab)
            }
        }
        
        return v
    }()
    
    var headerH:CGFloat = 210
    var cv = ComDynNavView()
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .white
        
        expectMenuList = getPersonMenuList()
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_back")?.withRenderingMode(.alwaysOriginal), style: .plain, target: self, action: #selector(back))
  
        let bgImg = UIImageView(image: UIImage(named: "common_bg"))
        bgImg.frame = self.view.bounds
        self.view.addSubview(bgImg)
        
        self.title = "我的"
     
        showMenuItemList = expectMenuList.compactMap { one -> MenuItem? in
            let mArr = MenuPool.filter{ $0.desc.unwrap == one}
            return mArr.first
        }
        showMenuItemList2 = expectMenuList2.compactMap { one -> MenuItem? in
            let mArr = MenuPool.filter{ $0.desc.unwrap == one}
            return mArr.first
        }
        
        collectionView.contentInset = UIEdgeInsets(top: headerH, left: 0, bottom: 20, right: 0)
        
        
        
        cv.frame = CGRect(x:0,y:0,width:KSGlobal.screenW,height:60)
        cv.titleLab.text = self.title
        cv.backButton.addTouchUpInSideAction { _ in
            self.navigationController?.popViewController(animated: true)
        }
        header.addSubview(cv)
        collectionView.addSubview(header)
        nameLab.text = USERINFO.zName
        
        // 忽略缓存, 因为重新上传图片后，地址也是不会变的
        img.kf.setImage(with: URL(string: USERINFO.headerUrl.unwrap), placeholder: UIImage(named: "icon_t"), options: [.forceRefresh])
        
        if checkPlatform(type: .zhuYouAn) {
            // 新友安云支持更新头像
            let tapGtr = UITapGestureRecognizer(target: self, action: #selector(changeHeaderImgClick))
            
            img.isUserInteractionEnabled = true
            img.addGestureRecognizer(tapGtr)
        }
        
        if let rlPostRank = USERINFO.rlPostRank {
            dotView.extHidden(hidden: false)
            dotView.lab.text = "P\(rlPostRank)"
            nameLab.snp.remakeConstraints { make in
                make.top.equalTo(img.snp.bottom).offset(10)
                make.centerX.equalToSuperview().offset(-16)
            }
        } else {
            dotView.extHidden(hidden: true)
            nameLab.snp.remakeConstraints { make in
                make.top.equalTo(img.snp.bottom).offset(10)
                make.centerX.equalToSuperview()
            }
        }
        
        companyLab.text = USERINFO.cUnitnameHs
        
        var deptNm = ""
        if USERINFO.deptNm.unwrap.count > 0 {
            deptNm = USERINFO.deptNm.unwrap
        }
        if USERINFO.rlPostNm.unwrap.count > 0 {
            if deptNm.count > 0 {
                deptNm += " | "
            }
            
            deptNm += USERINFO.rlPostNm.unwrap
            
            jobRespBtn.extHidden(hidden: false)
        } else {
            jobRespBtn.extHidden(hidden: true)
        }
        
        deptLab.text = deptNm
        collectionView.delegate = self
        collectionView.dataSource = self
        self.view.addSubview(collectionView)
        collectionView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
     
        if checkPlatform(type: .aoWang) {
            KSNetwork.shared.doRequest(API.getPostDutyExplain) { [weak self] (data: BaseResult<PersonInfoModel>) in
                if data.flag == TRUE {
                    self?.dutyExplain = (data.infoDic?["c_duty_explain"] as? String).unwrap
                }
            }
        }
    }
   
    //MARK: - Button Click
    @objc func back() {
        self.navigationController?.popViewController(animated: true)
    }
    
    @objc func changeHeaderImgClick() {
        if checkPlatform(type: .zhuYouAn ) {
            KSImagePicker.shared.showOnly4Crop(cameraAction: { [unowned self] img in
                self.uploadPic(headerImg: img)
            }, photoAction: { imgs, asset in
                self.uploadPic(headerImg: imgs.first!)
            })
        }
    }
    
    private func uploadPic(headerImg: UIImage) {
        if checkPlatform(type: .zhuYouAn) {
            var image = VideoImg()
            image.type = .image
            image.image = headerImg
            
            KSNetwork.shared.doRequest(API.headUploadPic(userId: USERINFO.staffId.unwrap, image: image)) { [weak self] (data:BaseResult<OperateResult>) in
                if data.flag == TRUE {
                    KSToast("上传成功")
                    self?.img.image = headerImg
                } else {
                    KSToast(data.errorCombine.unwrap)
                }
            }
        }
    }
    
    @objc func jobRespBtnClick() {
        let jobView = PersonJobRespView()
        jobView.show(WithJob: USERINFO.rlPostNm.unwrap, jobResp: dutyExplain)
    }
}

// MARK: - 代理和数据源
extension NewPersonVC {
    
   
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 2
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if section == 0 {
            return showMenuItemList.count
        } else {
            return showMenuItemList2.count
        }
        
        
        
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NewPersonCell.identifier, for: indexPath as IndexPath) as! NewPersonCell
        var shows:String? = ""
        var imgs:String? = ""
        if indexPath.section == 1 {
            shows = showMenuItemList2[indexPath.row].title
            imgs = showMenuItemList2[indexPath.row].imgStr

        } else {
            
             shows = showMenuItemList[indexPath.row].title
             imgs = showMenuItemList[indexPath.row].imgStr

        }
        cell.setLineHidden(indexPath.row == 0)
        cell.titleLab.text = shows
 
        cell.img.image = UIImage(named:imgs.unwrap)
 
        
        return cell
    }
    
    // 设置itemsize
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        let sectionW = self.view.ks_width - 24
        
     
      return CGSize(width: sectionW, height: 46)
   
             
   
    }
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var oneAc:((UIViewController)->())?
        if indexPath.section == 1 {
             oneAc = showMenuItemList2[indexPath.row].enterFunc

        } else {
            oneAc = showMenuItemList[indexPath.row].enterFunc
        }
        oneAc!(self)
        
        
        
    }
    
    
    
    
}
extension NewPersonVC : JJCollectionViewDelegateRoundFlowLayout_Swift{
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, borderEdgeInsertsForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 12, left: 12, bottom: 12, right: 12)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, configModelForSectionAtIndex section: Int) -> JJCollectionViewRoundConfigModel_Swift {
        let model = JJCollectionViewRoundConfigModel_Swift.init()
        model.cornerRadius = 8
        model.backgroundColor = UIColor(kshex:"#f9f9f9")
        
        
        return model;
        
    }
}
class NewPersonCell: BadgeCollectionViewCell {
    
   private lazy var line:UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(kshex:"#f1f1f1")
        return v
    }()
    
    lazy var img:UIImageView = {
        let view = UIImageView(frame: CGRect(x:10,y: (self.contentView.frame.height - 26)/2,width: 26,height:26))
        return view
    }()
    lazy var arrow:UIImageView = {
        let view = UIImageView(frame: CGRect(x:self.contentView.frame.width - 23,y: (self.contentView.frame.height - 12)/2,width: 7,height:12))
        view.image = UIImage(named: "arrow_person")
        return view
    }()
    lazy var titleLab:UILabel = {
       let lab = UILabel(frame: CGRect(x:60,y:0,width: 200,height:self.contentView.frame.height))
        lab.font = UIFont.boldSystemFont(ofSize: 15)
        lab.textColor = UIColor(kshex: "#2A304A")
        return lab
    }()
    lazy var contentLab:UILabel = {
        let lab = UILabel(frame: CGRect(x:self.contentView.frame.width - 120,y:0,width: 120,height:self.contentView.frame.height))
        lab.font = UIFont.systemFont(ofSize: 15)
        lab.textAlignment = .right
        lab.tintColor = #colorLiteral(red: 0.501960814, green: 0.501960814, blue: 0.501960814, alpha: 1)
        return lab
    }()
 
    func setLineHidden(_ flag:Bool) {
        self.line.isHidden = flag
    }
    convenience required init(coder : NSCoder){
        self.init()
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.initUtil()
    }
    
    func initUtil() {
        self.contentView.backgroundColor = .clear
         
        self.contentView.addSubview(img)
        self.contentView.addSubview(arrow)

        self.contentView.addSubview(titleLab)
        self.contentView.addSubview(line)
        self.contentView.addSubview(contentLab)
        
        line.snp.makeConstraints { make in
//            CGRect(x:10,y:self.contentView.frame.maxY - 1,width: KSGlobal.screenW - 20,height:1)
            make.left.equalToSuperview().offset(13)
            make.right.equalToSuperview().offset(-13)
            make.height.equalTo(1)
            make.top.equalToSuperview()
        }
        
    }
}
class DotVView:UIView {
    var cvView:UIView = {
        var v = UIView()
        return v
    }()
    var lab:UILabel = {
       var v = UILabel()
        v.textColor = .white
        return v
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(cvView)
        cvView.backgroundColor = UIColor(kshex: "#7487FF")
        cvView.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.height.width.equalToSuperview().multipliedBy(0.5)
            
        }
        addSubview(lab)
        lab.snp.makeConstraints { make in
            make.center.equalToSuperview()
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}
